<?php

class PostsController extends AppController {

    public $name = "Posts";
    public $helpers = array('Html', 'Form');

    public function isAuthorized($user) {
        if(!parent::isAuthorized($user)){
            if($this->action === 'add'){ //permissao para add apenas para usuarios logados
                return true;
            }
            if(in_array($this->action, array('edit','delete'))){
                $postId = $this->request->params['pass'][0];
                return $this->Post->isOwnedBy($postId, $user['id']);
            }
          return false;  
        }
    }
    public function index() {
        $this->set('posts', $this->Post->find('all'));
    }

    public function show($id = NULL) {
        $this->Post->id = $id;
        $this->set('post', $this->Post->read());
    }

    public function add() {
        if ($this->request->is('post')) {
            $this->request->data['Post']['user_id'] = $this->Auth->user('id'); //armazena id do usuario
            if ($this->Post->save($this->request->data)) {
                $this->Session->setFlash('Postagem adicionada com sucesso..');
                $this->redirect(array('action' => 'index'));
            }
        }
    }

    public function edit($id = NULL) {
        $this->Post->id = $id;
        if ($this->request->is('get')) {
            $this->request->data = $this->Post->read();
        } else {
            if ($this->Post->save($this->request->data)) {
                $this->Session->setFlash('Postagem atualizada com sucesso.');
                $this->redirect(array('action' => 'index'));
            }
        }
    }

}

?>